package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("common")
/**
 * 图片的上传和下载
 */
public class CommonController {

    @Value("${reggie.path}")   //动态加载配置类里的配置属性，reggie.path是存放磁盘的位置
    private String basePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取后面的字符串“.jpg”这几个不做处理  suffix翻译是后缀的意思
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") );
        //也可以用UUID获得随机名字
        String fileName =UUID.randomUUID().toString() + suffix;
        //判断是否存在目录，不存在自动创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            //目录不存在，创建一个新的目录
            dir.mkdirs();
        }
        try{
            file.transferTo(new File(basePath + fileName));
        }catch (IOException e) {
           e.printStackTrace();
        }

        return R.success(fileName);
    }


    /**
     * 功能未完成！回显到浏览器可能没实现，到最后在测试
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流,通过输出流将文件写回浏览器,在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes, 0, length);
                //刷新
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
